package com.younion.action.manage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.google.common.collect.Maps;
import com.younion.business.ICustomerService;
import com.younion.business.IFavourableEntityService;
import com.younion.business.IFavourableService;
import com.younion.business.IFavourableTypeService;
import com.younion.business.IShopService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.SysConstants;
import com.younion.common.paginator.Paginator;
import com.younion.common.util.ImageFileUtil;
import com.younion.util.UUIDUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.FavourableEntityVO;
import com.younion.vo.FavourableTypeVO;
import com.younion.vo.ShopVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author jillchan
 */
public class FavourableEntityAction extends BaseAction {

	protected static final Log logger = LogFactory
			.getLog(FavourableEntityAction.class);
	private IFavourableTypeService favourableTypeService = null;

	private IFavourableEntityService favourableEntityService = null;

	private IShopService shopService = null;

	private ICustomerService customerService = null;

	private IFavourableService favourableService = null;

	private FavourableEntityVO favourableEntityVO = new FavourableEntityVO();

	private FavourableTypeVO favourableTypeVO = new FavourableTypeVO();

	private List<FavourableEntityVO> favourableEntityList = new ArrayList<FavourableEntityVO>();

	private List<FavourableTypeVO> favourableTypeList;

	private UUIDUtil uUIDUtil = new UUIDUtil();

	private String searchType;

	/**
	 * 列表：翻页区；数据区
	 */
	@RequiresPermissions("listFavourableEntity")
	public String listFavourableEntity() {
		try {
			Map<String, Integer> paramMap = new HashMap<String, Integer>();
			CustomerVO customer = getSessionUser().getCustomer();
			Integer userCustomerId = null;
			if (customer != null) {
				userCustomerId = customer.getId();
			}
			if (favourableEntityVO != null) {
				if (userCustomerId != null) {
					favourableEntityVO.setCustomerId(userCustomerId);
				}
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils
						.describe(favourableEntityVO));
			}

			if (this.searchType != null) {
				String customerId = request.getParameter("customerId");
				if (customerId != null && !customerId.equals("")) {
					paramMap.put("customerId", Integer.valueOf(customerId));
					paramMap.put("ltreleaseChannel", Integer.valueOf("2"));
				}
			}
			// 获取总记录数
			int total = favourableEntityService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);

			favourableEntityList = favourableEntityService.get(paramMap,
					paginator);
			// System.out.println("favourableEntityList.size()========"+favourableEntityList.size());
			// System.out.println("favourable_name==="+favourableEntityList.get(0).getName());
			// 保存分页对象
			this.savaPaginator(paginator);
			this.addLog(2, "查询优惠券实体列表", "查询优惠券实体列表", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addFavourableEntity")
	public String addFavourableEntity() {
		try {
			CustomerVO customer = getSessionUser().getCustomer();
			if (customer != null) {
				request.setAttribute("customerId", customer.getId());
				request.setAttribute("customerName", customer.getName());
			}
			String code = uUIDUtil.getUuid().toString();
			favourableEntityVO.setCode(code);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editFavourableEntity")
	public String editFavourableEntity() {
		try {
			favourableEntityVO = favourableEntityService
					.getById(favourableEntityVO.getId().toString());

			String shopCodes = favourableEntityVO.getShopCode();
			if (shopCodes != null && !"".equals(shopCodes)) {
				String[] shopIds = shopCodes.split(",");
				String shopNames = "";
				int length = shopIds.length;
				for (int i = 0; i < length; i++) {
					if (shopService.getById(shopIds[i]) != null) {
						ShopVO shop = shopService.getById(shopIds[i]);
						if (i == (length - 1)) {
							shopNames += shop.getName();
						} else {
							shopNames += shop.getName() + ",";
						}
					}
				}
				request.setAttribute("shopNames", shopNames);
			}
			String customerId = favourableEntityVO.getCustomerId().toString();
			CustomerVO customer = customerService.getById(customerId);
			String customerName = customer.getName();
			request.setAttribute("customerName", customerName);
			// 页面根据userCustomerId是否为空判断是否为超级用户
			CustomerVO userCustomer = getSessionUser().getCustomer();
			if (userCustomer != null) {
				request.setAttribute("userCustomerId", userCustomer.getId());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveFavourableEntity")
	public String saveFavourableEntity() {
		try {
			if ("".equals(favourableEntityVO.getValidTimeFrom())) {
				favourableEntityVO.setValidTimeFrom(null);
			}
			if ("".equals(favourableEntityVO.getValidTimeTo())) {
				favourableEntityVO.setValidTimeTo(null);
			}
			int favourableEntityKey = favourableEntityService
					.saveReturnKey(favourableEntityVO);
			ImageFileUtil
					.processImageFiles(favourableEntityKey, "1,2", request);
			request.setAttribute("refreshNavTabId", "favourableEntityList");
			String id = favourableEntityVO.getId() == null ? ""
					: favourableEntityVO.getId().toString();
			String log = "".equals(id) ? "添加优惠券实体" : "更新优惠券实体";
			this.addLog(3, log + id, log, getSessionUser());

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("deleteFavourableEntity")
	public String deleteFavourableEntity() {
		try {
			String realPath = request.getSession().getServletContext()
					.getRealPath(SysConstants.FavourableEntity_IMG_PATH);
			String pkId = request.getParameter("ids");
			List<String> list = new ArrayList<String>();
			Map<String, Integer> map = new HashMap<String, Integer>();
			for (String id : pkId.split(",")) {
				map.put("favEntId", Integer.valueOf(id));
				int count = favourableService.getCountByMap(map);
				if (count == 0) {
					list.add(id);
					File directory = new File(realPath + File.separator + id);

					FavourableEntityVO fav = favourableEntityService
							.getById(id);
					String fileNames = fav.getNonactivatedPic() + ","
							+ fav.getActivatedPic();
					ImageFileUtil.deleteImage(directory, fileNames, true);
				}
				map.clear();
			}
			favourableEntityService.remove(list);
			request.setAttribute("refreshNavTabId", "favourableEntityList");
			String log = "删除优惠券实体";
			this.addLog(5, log + pkId, log, getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 查看鿴
	 */
	@RequiresPermissions("viewFavourableEntity")
	public String viewFavourableEntity() {
		try {
			favourableEntityVO = favourableEntityService
					.getById(favourableEntityVO.getId().toString());
			favourableTypeVO = favourableTypeService.getById(favourableEntityVO
					.getFavourableTypeId().toString());
			String shopCodes = favourableEntityVO.getShopCode();
			String shopNames = "";
			if (shopCodes != null && !"".equals(shopCodes)) {
				String[] shopIds = shopCodes.split(",");
				int length = shopIds.length;
				for (int i = 0; i < length; i++) {
					if (shopService.getById(shopIds[i]) != null) {
						ShopVO shop = shopService.getById(shopIds[i]);
						if (i == (length - 1)) {
							shopNames += shop.getName();
						} else {
							shopNames += shop.getName() + ",";
						}
					}
				}
				request.setAttribute("shopNames", shopNames);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}

	/**
	 * 查看图片
	 */
	public void viewImage() throws IOException {
		String id = request.getParameter("id");
		String picname = request.getParameter("picname");
		String realPath = request.getSession().getServletContext().getRealPath(
				SysConstants.FavourableEntity_IMG_PATH);
		System.out.println("realPath:" + realPath);
		if (StringUtils.isNotEmpty(picname) && StringUtils.isNotEmpty(id)) {
			File file = new File(realPath + File.separator + id, picname);
			if (file.exists()) {
				FileInputStream fIS = null;
				OutputStream servletOut = null;
				try {
					response.reset();
					response.setContentType("image/jpeg");
					response.setContentLength((int) file.length());
					fIS = new FileInputStream(file);
					servletOut = response.getOutputStream();
					byte[] buf = new byte[1024];
					int iRead = 0;
					while (true) {
						iRead = fIS.read(buf);
						if (iRead > 0) {
							servletOut.write(buf, 0, iRead);
						} else
							break;
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						fIS.close();
						servletOut.flush();
						servletOut.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public FavourableEntityVO getFavourableEntityVO() {
		return favourableEntityVO;
	}

	public void setFavourableEntityVO(FavourableEntityVO favourableEntityVO) {
		this.favourableEntityVO = favourableEntityVO;
	}

	public void setFavourableEntityService(
			IFavourableEntityService favourableEntityService) {
		this.favourableEntityService = favourableEntityService;
	}

	public void setFavourableTypeService(
			IFavourableTypeService favourableTypeService) {
		this.favourableTypeService = favourableTypeService;
	}

	public List<FavourableEntityVO> getFavourableEntityList() {
		return favourableEntityList;
	}

	public void setFavourableEntityList(
			List<FavourableEntityVO> favourableEntityList) {
		this.favourableEntityList = favourableEntityList;
	}

	public List<FavourableTypeVO> getFavourableTypeList() {
		if (this.favourableTypeList == null) {
			try {
				Map params = Maps.newHashMap();
				CustomerVO customer = getSessionUser().getCustomer();
				if (customer != null) {
					params.put("customerId", customer.getId());
					favourableTypeList = (List<FavourableTypeVO>) favourableTypeService
							.getByMap(params);
				} else {
					favourableTypeList = (List<FavourableTypeVO>) favourableTypeService
							.getAll();
				}
			} catch (Exception e) {
			}
		}
		return favourableTypeList;
	}

	public void setFavourableTypeList(List<FavourableTypeVO> favourableTypeList) {
		this.favourableTypeList = favourableTypeList;
	}

	public FavourableTypeVO getFavourableTypeVO() {
		return favourableTypeVO;
	}

	public void setFavourableTypeVO(FavourableTypeVO favourableTypeVO) {
		this.favourableTypeVO = favourableTypeVO;
	}

	public void setShopService(IShopService shopService) {
		this.shopService = shopService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}

	public void setFavourableService(IFavourableService favourableService) {
		this.favourableService = favourableService;
	}

}